<template>
    <div>
        <v-container fluid>
            <h4 class="mb-3">贷款物料管理</h4>

            <v-row align="center" dense>
                <v-col :md="2" :sm="6">
                    <AutocompleteOrg item-key="org_code" v-model="queryOrg"></AutocompleteOrg>
                </v-col>

                 <v-col :md="2" :sm="6">
                    <AutocompleteUser label="负责人" v-model="queryUser" item-text="name"></AutocompleteUser>
                </v-col>

<!--                <v-col :md="2" :sm="6">-->
<!--                    <v-select :items="catetoryItem"  clearable v-model="queryCategory" label="类别"> </v-select>-->
<!--                </v-col>-->


                <v-col :md="1" :sm="6">
                    <v-select :items="statusItem"  clearable v-model="queryStatus" label="状态"> </v-select>
                </v-col>

                <v-col :md="2" :sm="6">
                    <v-text-field
                        label="编号"
                        v-model="queryNumber"
                        clearable
                        type="text">
                    </v-text-field>
                </v-col>

                <v-col :md="1" :sm="6">
                    <v-text-field
                        label="渠道"
                        v-model="queryCustomField"
                        clearable
                        type="text">
                    </v-text-field>
                </v-col>

                <v-col :md="1" :sm="6">
                    <v-text-field
                        label="城市"
                        v-model="queryCity"
                        clearable
                        type="text">
                    </v-text-field>
                </v-col>


                <v-col :md="1" :sm="6">
                     <v-text-field
                        label="姓名"
                        v-model="queryName"
                        clearable
                        type="text">
                    </v-text-field>
                </v-col>

                <v-col :md="1" :sm="6">
                     <v-text-field
                        label="手机号"
                        v-model="queryMobile"
                        clearable
                        type="text">
                    </v-text-field>
                </v-col>



                <v-col :md="4" :sm="6">
                    <v-btn
                        dark
                        class="mb-2 mr-2"
                        @click="query()"
                    >查询
                    </v-btn>

                    <v-btn
                        dark
                        class="mb-2 mr-2"
                        @click="reset()"
                    >重置
                    </v-btn>

                    <v-menu bottom offset-y v-if="is_supper">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn
                                dark
                                v-bind="attrs"
                                v-on="on"
                                class="mb-2 mr-2"
                            >
                            导入
                            </v-btn>
                        </template>

                        <v-list>
                            <v-list-item :to="`/loan/import/general`" >
                                <v-list-item-title>银行综合贷款</v-list-item-title>
                            </v-list-item>
                            <v-list-item :to="`/loan/import/mortgage-tax`" >
                                <v-list-item-title>企业税贷</v-list-item-title>
                            </v-list-item>
                            <v-list-item :to="`/loan/import/mortgage-house`" >
                                <v-list-item-title>房屋抵押贷</v-list-item-title>
                            </v-list-item>
                            <v-list-item :to="`/loan/import/mortgage-car`" >
                                <v-list-item-title>车辆抵押贷</v-list-item-title>
                            </v-list-item>
                            <v-list-item :to="`/loan/import/credit-provident`" >
                                <v-list-item-title>公积金信用贷</v-list-item-title>
                            </v-list-item>
                        </v-list>
                    </v-menu>

                    <v-menu bottom offset-y  v-if="is_supper || is_manager">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn
                                v-bind="attrs"
                                v-on="on"
                                class="mb-2 mr-2"
                                :disabled="selected.length == 0"
                            >
                            操作
                            </v-btn>
                        </template>

                        <v-list>
                            <v-list-item :disabled="selected.length == 0" @click="allocateDialog = true">
                                    指派
                            </v-list-item>
                        </v-list>
                    </v-menu>
                </v-col>
            </v-row>
        </v-container>

        <v-data-table
            item-key="id"
            :headers="headers"
            :items="items"
            class="overflow-x-auto"
            style="white-space: nowrap"
            no-data-text="没有数据..."
            :page.sync="pageNo"
            :items-per-page="pageSize"
            hide-default-footer
            calculate-widths
            show-select
            v-model="selected"
        >
            <template v-slot:[`item.id`]="{ item }">
                <router-link :to="`/loan/${item.id}`" class="text-decoration-none">{{item.id}}</router-link>
            </template>

            <template v-slot:[`item.name`]="{ item }">
                <span>姓名：{{item.name}}</span> <br/>
                <span v-if="item.user">负责人: {{item.user.name}}</span>
                <span v-else>负责人: --</span>
            </template>


            <template v-slot:[`item.custom_field`]="{ item }">
                <span>类别：{{item.category_name}}</span> <br/>
                <span v-if="item.custom_field">渠道: {{item.custom_field}}</span>
                <span v-else>渠道: --</span>

            </template>



            <template v-slot:[`item.amount`]="{ item }">
                <span>{{item.amount_start_zh}}</span> - <span>{{item.amount_end_zh}}</span>
            </template>
             <template v-slot:[`item.province_city`]="{ item }">
                <span>{{item.province}}</span>  <span>{{item.city}}</span>
            </template>
            <template v-slot:[`item.actions`]="{ item }">
                 <v-btn small depressed :to="`/loan/${item.id}`" color="primary">详情</v-btn>
                 <v-btn small depressed  @click="deleteItem(item)">删除</v-btn>
            </template>
        </v-data-table>
        <v-dialog v-model="dialogDelete" max-width="400px">
            <v-card v-if="itemToDelete">
                <v-card-title class="text-h5">删除 {{itemToDelete.title}}?</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn depressed @click="dialogDelete = false">取消</v-btn>
                    <v-btn depressed color="error" @click="confirmDelete" :loading="deleting">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-row v-if="items.length > 0 && totalPage >= 1" class="mt-2">
            <v-col cols="12">
                <v-pagination
                    v-model="pageNo"
                    :length="totalPage"
                    :total-visible="7"
                    @input="onPageChange"
                ></v-pagination>
            </v-col>
        </v-row>

        <v-dialog
            v-model="allocateDialog"
            persistent
            max-width="400px"
        >
            <v-form ref="form">
                <v-card>
                    <v-card-title>
                        <span class="text-h5">指派</span>
                    </v-card-title>
                    <v-card-text>

                    <v-row>
                        <v-col cols="12">
                            <v-select  label="组织/个人" v-model="allocateType" :rules="[rules.required]" :items="[{text: '组织', value: 1}, {text: '个人', value: 2}]">
                            </v-select>
                        </v-col>
                    </v-row>

                    <v-row v-if="allocateType == 1" >
                        <v-col cols="12">
                            <AutocompleteOrg :rules="[rules.required]" v-model="allocateOrg"></AutocompleteOrg>
                        </v-col>
                    </v-row>
                     <v-row  v-if="allocateType == 2" >
                        <v-col cols="12">
                            <AutocompleteUser :rules="[rules.required]" v-model="allocateUser"></AutocompleteUser>
                        </v-col>
                    </v-row>

                    </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn  depressed   @click="allocateDialog = false" :disabled="allocating">
                            关闭
                        </v-btn>
                        <v-btn   depressed  color="primary" dark :loading="allocating" @click="allocate">
                            确定
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-form>
        </v-dialog>
    </div>
</template>

<script>
    import axios from "axios";
    import AutocompleteOrg from "../../widgets/AutocompleteOrg.vue";
    import AutocompleteUser from "../../widgets/AutocompleteUser.vue";
    import { mapGetters } from 'vuex';

    export default {
        data: () => ({
            headers: [
                // { text: '序号', value: 'id' },
                { text: '编号', value: 'number' },
                { text: '姓名', value: 'name' },
                { text: '手机号', value: 'mobile' },
                { text: '需要金币', value: 'need_ticket' },
                { text: '状态', value: 'status_name' },
                { text: '渠道', value: 'custom_field' },
                // { text: '组织名称', value: 'org.name' },
                { text: '省市', value: 'province_city' },
                { text: '贷款额度', value: 'amount' },
                { text: '申请时间', value: 'apply_at' },
                // { text: '状态', value: 'status_name' },
                { text: '操作', value: 'actions',fixed:true, sortable: false },
            ],
            items: [],
            pageNo: 1,
            pageSize: 20,
            totalPage: 0,
            selected: [],
            queryName: '',
            queryMobile: '',
            queryOrg: null,
            queryUser: null,
            queryNumber: null,
            queryCustomField: null,
            queryCity: null,
            queryCategory: '',
            queryStatus: '',
            allocating: false,
            allocateDialog: false,
            allocateType: 1,
            allocateOrg: null,
            allocateUser: null,
            rules: {
                required: value => !!value || '必填',
            },
            dialogDelete: false,
            deleting: false,
            itemToDelete: null,
            catetoryItem: [
                { value:  'general', text: '银行综合贷款' },
                { value:  'credit-provident', text: '公积金信用贷' },
                { value: 'mortgage-car', text: '车辆抵押贷' },
                { value: 'mortgage-house', text: '房屋抵押贷' },
                { value: 'mortgage-tax', text: '企业税贷' },
            ],
            statusItem: [
                { value:  'error', text: '无效订单' },
                { value:  'have', text: '已抢单' },
                { value:  'not-have', text: '未抢单' },
                { value:  'refund', text: '退款订单' },
            ],
        }),

        components: {
            AutocompleteOrg: AutocompleteOrg,
            AutocompleteUser: AutocompleteUser
        },

        computed: {
            ...mapGetters([
                'is_supper',
                'is_manager'
            ]),
        },

        created() {
            this.loadList();
        },

        methods: {
            confirmDelete() {
                this.deleting = true;
                const that = this;
                axios.delete(`/loan/delete/${this.itemToDelete.id}`).then((response) => {
                    if (response.data.code == 0) {
                        this.loadList();
                        this.dialogDelete = false;
                        this.itemToDelete = null;
                    }
                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                })
                    .catch(function () {})
                    .then(function () {
                        that.deleting = false;
                    });
            },
            deleteItem(item) {
                this.itemToDelete = item;
                this.dialogDelete = true;
            },
            loadList() {
                this.loading = true;
                const that = this;
                const params = Object.entries({
                    pageSize: this.pageSize,
                    page: this.pageNo,
                    name: this.queryName,
                    mobile: this.queryMobile,
                    org_code: this.queryOrg ? this.queryOrg.org_code : '',
                    user_id: this.queryUser ? this.queryUser.id : '',
                    city: this.queryCity ? this.queryCity : '',
                    number: this.queryNumber ? this.queryNumber : '',
                    custom_field: this.queryCustomField ? this.queryCustomField : '',
                    category: this.queryCategory,
                    status: this.queryStatus,
                }).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {});
                axios.get(`/loan`, {
                    params: params
                }).then((response) => {
                    if(response.data.data.length >= 0) {
                        this.items = response.data.data;
                        this.totalPage = response.data.last_page;
                    }
                })
                .catch(function () {})
                .then(function () {
                    that.loading = false;
                });
            },

            onPageChange() {
                this.loadList();
            },

            query() {
                this.pageNo = 1;
                this.loadList();
            },

            reset() {
                this.queryName = '';
                this.queryMobile = '';
                this.queryOrg = null;
                this.queryUser = null;
                this.queryCategory = '';
                this.queryStatus = '';
                this.pageNo = 1;
                this.loadList();
            },

            allocate() {
                if (!this.$refs.form.validate()) {
                  return;
                }

                const that = this;
                that.allocating = true;

                axios.post("/loan/allocate", {
                    loan_ids: this.selected.map(v => v.id),
                    org_id: this.allocateOrg ? this.allocateOrg.id : 0,
                    user_id: this.allocateUser ? this.allocateUser.id : 0,
                }).then((response) => {
                    if (response.data.code == 0) {
                        that.loadList();
                        that.selected = [];
                        that.allocateDialog = false;
                    }

                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                }).catch(function () {})
                .then(function () {
                     that.allocating = false;
                });
            }
        }
    }
</script>
